<?php

namespace PhpSeverless;

class PhpCGI
{
    public $host = '127.0.0.1';

    public $port = '9001';

    public $bin = '/var/lang/php7/bin/php-cgi';

    public $ini = '';

    public function __construct($options = [])
    {
        foreach ($options as $key => $value) {
            if ($key == 'bin') {
                $value = realpath($value);
            }
            $this->$key = $value;
        }

        if (!$this->isRunning()) {
            $this->start();
        }
    }

    public function start()
    {
        $host = $this->host;
        $port = $this->port;

        $cmd = [
            'nohup',
            $this->bin,
            '-b', "{$host}:{$port}",
        ];

        if ($this->ini) {
            $cmd = array_merge($cmd, [
                '-c', $this->ini,
            ]);
        }

        $cmd = array_merge($cmd, [
            '>/tmp/cgi.log',
            '2>&1',
            '&',
        ]);

        $command = implode(' ', $cmd);

        echo $command;
        exec($command, $output, $result);

        $start = microtime(true);
        do {
            if (microtime(true) - $start > 1) {
                echo \file_get_contents('/tmp/cgi.log');
                die("Webserver failed to start within one second\n");
            }
            usleep(1000);
            $fp = @fsockopen($this->host, $this->port, $errno, $errstr, 1);
        } while ($fp == false);
        fclose($fp);
    }

    public function isRunning()
    {
        $fp = @fsockopen($this->host, $this->port, $errno, $errstr, 1);
        return false != $fp;
    }
}
